package com.taotao.cart.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.taotao.cart.bean.TbUser;
import com.taotao.cart.service.UserService;
import com.taotao.cart.threadlocal.UserThreadLocal;
import com.taotao.common.util.CookieUtils;

public class UserLoginHandlerInterceptor implements HandlerInterceptor {

	private  static final String  TOKEN_NAME = "TT_TOKEN";
	
	@Autowired
	private UserService userService;
	
	/**
	 * 主要目的是判断当前用户是否为登录状态
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		String token = CookieUtils.getCookieValue(request, TOKEN_NAME);
		if(StringUtils.isEmpty(token)) {
			return true;
		}
		TbUser user = userService.queryUserByToken(token);
		if(user == null) {
			return true;
		}
		UserThreadLocal.set(user);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		UserThreadLocal.set(null);//线程池的情况下，线程已经存在变量，所以需要清空操作
	}

}
